<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\UserVali;
use App\Model\Backstage\CustomerFollowSourde;
use App\Model\Backstage\User;
use App\Tool\Error;
use Illuminate\Http\Request;
use Validator;

/**
 * Class UserController
 * @package App\Http\Controllers\Backstage
 * 登录控制器
 * date:2018-4-30
 * author:lxy
 */
class LoginController extends Controller
{
    protected $user;

    //当前客户端所在省份
    public $province = '';
    public $province_code;
    //当前客户端所在城市名称
    public $city = '';
    public $city_code = '';
    //当前IP
    public $IP;
    //淘宝IP库
    public $taobaoAddress = 'http://ip.taobao.com/service/getIpInfo.php';


    public function __construct(Request $request)
    {
//        $this->IP = $request->getClientIp();
        $this->IP = '36.47.165.139';
        $this->getIpAddress();
        $this->user = new User();
    }
    /**
     * 根据公网IP地址获取对应城市
     */
    public function getIpAddress(){
        //淘宝IP库
        $ip_res = @file_get_contents($this->taobaoAddress."?ip=$this->IP");
        $ip_res = json_decode($ip_res,true);
        if($ip_res['code'] == 0){
            $this->province = $ip_res['data']['region'];
            $this->city = $ip_res['data']['city'];
        }
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 用户登录
     */
    public function index(Request $request,User $User)
    {
        $params = $request->all();
        $vali = UserVali::loginValidate($params);
        if(!$vali){
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $this->user->loginUser($params,  $this->province,  $this->city,  $this->IP);
        if ($res === -4) {
            //账号不存在
            return $this->error(Error::USERNAME_NULL);
        }
        if ($res === -5) {
            //账号被禁用
            return $this->error(Error::ACCOUNT_DISABLE);
        }
        if ($res === -6) {
            //账号被删除
            return $this->error(Error::ACCOUNT_DEL);
        }
        if ($res === -1) {
            //公司还在审核中不能登录
            return $this->error(Error::AUDIT);
        }
        if ($res === -2) {
            //公司账号到期没有续费无法登录
            return $this->error(Error::NO_RENEWAL);
        }
        if ($res === -3) {
            //未知错误 请联系管理员
            return $this->error(Error::PLEASE_CONTACT_ADMIN);
        }
        if($res){
            return $this->success('ok',$res);
        }else{
            return $this->error(Error::PASSWORD_ERROR);
        }

    }



}